#!/bin/sh
task_id=$1
reload_undone=${2:-false}
batch_no="batch20190607"

if [ $# -lt 1 ]; then
  echo "parameter error, need one parameter, while current have $#..."
  echo "example: ./start_task.sh 1"
  exit 1
fi

# setup
base_path="/home/ec2-user"
log_file_base_path="$base_path/logs"
mkdir $log_file_base_path -p

log_file_name="$task_id.$(date "+%Y%m%d").out"
log_file_path="$log_file_base_path/$log_file_name"

tasks_name="tasks$task_id"
tasks_path="$base_path/$batch_no/$tasks_name"

execution_path="$base_path/gitsource/azspider/spiders"

# reload_undone
tasks_backup_path="$base_path/tasks_backup"
mkdir $tasks_backup_path/$tasks_name -p

if $reload_undone; then
  echo "reload undone set to true..."
  mv "$base_path/$tasks_name/undone_node.json" "$tasks_backup_path/$tasks_name/undone_node_$(date "+%Y%m%d-%H%M%S").json"
  echo "moved $base_path/$tasks_name/undone_node.json to $tasks_backup_path/$tasks_name/undone_node_$(date "+%Y%m%d-%H%M%S").json"
else
  echo "reload undone set to false..."
fi

# killed existing service
process_id=$(ps -aef | grep amazonAnsiListingSpider.py | grep $tasks_name | grep $batch_no | grep -v grep | awk '{print $2}')
if [ -z "$process_id" ];then
  echo "not existing service running $tasks_name..."
else
  kill -9 $process_id
  echo "killed existing service: $tasks_name, process_id: $process_id..."
fi

cd $execution_path

nohup python amazonAnsiListingSpider.py $task_id $tasks_path $batch_no > $log_file_path 2>&1 &

sleep 2s
echo "task should be started, here displaying the task status..."
ps -ef | grep "amazonAnsiListingSpider.py"

echo "displaying logging... you can press ctrl + c to interrupt anytime, won't stop the task..."
tail -f -n 100 $log_file_path